package com.future.mayi.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.DateUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.statusbarlibrary.StatusBarUtils;
import com.future.baselib.view.MyScrollView;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.dialog.GoodsSelectDialog;
import com.future.mayi.dialog.KefuDialog;
import com.future.mayi.fragment.GoodsSelectFragment;
import com.future.mayi.fragment.IndexFragment;
import com.future.mayi.model.AddressModel;
import com.future.mayi.model.GoodsDetailModel;
import com.future.mayi.model.GoodsModel;
import com.future.mayi.model.GoodsParamModel;
import com.future.mayi.model.KefuModel;
import com.future.mayi.model.PackCommonModel;
import com.future.mayi.model.SpecListModel;
import com.future.mayi.model.UserInfoModel;
import com.future.mayi.model.interfaces.OnItemPageClick;
import com.future.mayi.qsale.activity.CartActivity;
import com.future.mayi.qsale.model.CartListModel;
import com.future.mayi.response.AddressResponse;
import com.future.mayi.response.GoodsResponse;
import com.future.mayi.response.KefuResponse;
import com.future.mayi.response.UserInfoResponse;
import com.future.mayi.utils.ClickUtils;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.HtmlFormat;
import com.future.mayi.utils.PriceUtils;
import com.future.mayi.utils.SharedPreferencesUtils;
import com.future.mayi.view.GoodsSkuView;
import com.future.mayi.view.SampleCoverVideo;
import com.future.mayi.widget.GoodsTitleView;
import com.shuyu.gsyvideoplayer.GSYVideoManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class GoodsActivity extends BaseActivity implements OnItemPageClick, MyScrollView.onScrollListener {


    private boolean statusBar = false;
    private int statusBarHeight;
    @BindView(R.id.rl_main)
    RelativeLayout rlMain;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.scroll_view)
    MyScrollView scrollView;
    @BindView(R.id.layout_goods_bottom)
    LinearLayout layoutGoodsBottom;
    @BindView(R.id.img_view)
    GoodsTitleView imgView;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_freight)
    TextView tvFreight;
    @BindView(R.id.tv_old_price)
    TextView tvOldPrice;
    @BindView(R.id.tv_price_name)
    TextView tvPriceName;
    @BindView(R.id.tv_goods_title)
    TextView tvGoodsTitle;

    @BindView(R.id.tv_goods_sub_title)
    TextView tvGoodsSubTitle;
    @BindView(R.id.ll_describe)
    LinearLayout llDescribe;
    @BindView(R.id.rl_describe)
    View rlDescribe;
    @BindView(R.id.view_describe)
    View viewDescribe;
    @BindView(R.id.tv_batch)
    TextView tvBatch;

    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_title_w)
    LinearLayout llTitleW;
    @BindView(R.id.iv_title_left_t)
    ImageView ivTitleLeftT;
    @BindView(R.id.ll_title_t)
    LinearLayout llTitleT;
    @BindView(R.id.tv_service)
    TextView tvService;
    @BindView(R.id.tv_car)
    TextView tvCar;
    @BindView(R.id.tv_goods_count)
    TextView tvGoodsCount;
    @BindView(R.id.view_add_car)
    View viewAddCar;
    @BindView(R.id.view_pay)
    View viewPay;
    @BindView(R.id.ll_account_state)
    View llAccountState;
    @BindView(R.id.tv_account_state)
    TextView tvAccountState;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.video_view_detail)
    SampleCoverVideo videoViewDetail;
    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.sku_view)
    GoodsSkuView skuView;
    @BindView(R.id.ll_zhuan)
    View llZhuan;
    @BindView(R.id.tv_car_rebate)
    TextView tvCarRebate;
    @BindView(R.id.tv_pay_rebate)
    TextView tvPayRebate;
    @BindView(R.id.tv_zhuan_price)
    TextView tvZhuanPrice;

    private LayoutInflater mInflater;

    private int goodsId = -1;
    private String goods_code = null;
    private GoodsModel goodsModel;
    private int carList = 0;

    //邮费
    private double freight;
    //地址
    private AddressModel addressModel;

    public static void startActivity(Context context, int goodsId) {
        Intent intent = new Intent(context, GoodsActivity.class);
        intent.putExtra("goodsId", goodsId);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, String goods_code) {
        Intent intent = new Intent(context, GoodsActivity.class);
        intent.putExtra("goods_code", goods_code);
        context.startActivity(intent);
    }


    @Override
    protected void initLayout() {
        if (StatusBarUtils.setStatusBarTranslucent(getWindow(), true)) {
            statusBar = true;
            statusBarHeight = CommonUtils.getStatusBarHeight(this);
            StatusBarUtils.setStatusBarColor(getWindow(), Color.TRANSPARENT, false);
        }
        mInflater = LayoutInflater.from(this);
        setContentView(R.layout.activity_goods);
    }


    @Override
    protected void initView() {
        if (statusBar) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rlTitle.getLayoutParams();
            layoutParams.height = CommonUtils.dip2px(mContext, 45) + statusBarHeight;
        }
        tvOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setHorizontalScrollBarEnabled(false);
        if (videoViewDetail.getLayoutParams() != null)
            videoViewDetail.getLayoutParams().height = (int) ((CommonUtils.getScreenSize(mContext)[0] - CommonUtils.dip2px(mContext, 20)) * (157.0f / 327.0f));
        //增加title
        videoViewDetail.getTitleTextView().setVisibility(View.GONE);
        //设置返回键
        videoViewDetail.getBackButton().setVisibility(View.GONE);
        //设置全屏按键功能
        videoViewDetail.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                videoViewDetail.startWindowFullscreen(mContext, false, true);
            }
        });
        //防止错位设置
        videoViewDetail.setPlayTag(String.valueOf(hashCode()));
        videoViewDetail.setPlayPosition(0);
        //是否根据视频尺寸，自动选择竖屏全屏或者横屏全屏
        videoViewDetail.setAutoFullWithSize(true);
        //音频焦点冲突时是否释放
        videoViewDetail.setReleaseWhenLossAudio(false);
        //全屏动画
        videoViewDetail.setShowFullAnimation(true);
        //小屏时不触摸滑动
        videoViewDetail.setIsTouchWiget(false);
        videoViewDetail.setBtnHeight(CommonUtils.dip2px(mContext, 46));
    }

    @Override
    protected void initDates() {
        if (getIntent() != null) {
            goodsId = getIntent().getIntExtra("goodsId", goodsId);
            if (goodsId == -1) {
                try {
                    goodsId = Integer.valueOf(getIntent().getStringExtra("goodsId"));
                } catch (Exception e) {
                }
            }
        }
        if (goodsId == -1 && TextUtils.isEmpty(goods_code)) {
            finish();
            return;
        }
        goodsModel = new GoodsModel();
        goodsModel.setDetail(new GoodsDetailModel());
        goodsModel.getDetail().setGoods_id(goodsId);
        getPackCommon();
        getGoodsData();
    }

    @Override
    protected void initListener() {
        scrollView.setListener(this);
    }


    @OnClick({R.id.tv_batch, R.id.iv_title_left, R.id.iv_title_left_t, R.id.iv_title_right_t, R.id.ll_select_city, R.id.tv_service, R.id.tv_car, R.id.view_add_car, R.id.view_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.ll_select_city:
                Intent intent = new Intent(this, AddressActivity.class);
                intent.putExtra("isSelect", true);
                startActivityForResult(intent, 221);
                break;
            case R.id.iv_title_left:
            case R.id.iv_title_left_t:
                onBackPressed();
                break;
            case R.id.iv_title_right_t:
                break;
            case R.id.tv_service:
                new KefuDialog(this).show(0);
                break;
            case R.id.tv_car:
                if (ClickUtils.isNoLogin(this, true)) return;
                startActivity(new Intent(this, CartActivity.class));
                break;
            case R.id.tv_batch:
            case R.id.view_add_car:
            case R.id.view_pay: {
                if (ClickUtils.isNoLogin(this, true)) return;
                if (userInfoModel == null) return;
                if (goodsModel == null) return;
                if (packCommonModel == null) return;
                if (identity != 1) {
                    if (userStatus == 99) {
                        App.clear();
                        Intent loginActivityIntent = new Intent();
                        loginActivityIntent.setClass(mContext, LoginActivity.class);
                        mContext.startActivity(loginActivityIntent);
                        return;
                    }
                    if (userStatus == 0 || userStatus == 10) {
                        startActivity(new Intent(mContext, AccountStateActivity.class));
                    } else if (userStatus == -1) {
                        if (packCommonModel.getIs_open() == 0) {
                            startActivity(new Intent(mContext, AccountApplyActivity.class));
                        } else {
                            if (packCommonModel.getPack_goods_id() == goodsId) {
                                showSku(false);
                            } else {
                                GoodsActivity.startActivity(mContext, packCommonModel.getPack_goods_id());
                            }
                        }
                    } else if (userStatus == 20) {
                        GoodsAllOrderActivity.startActivity(mContext, 0);
                    }
                    return;
                }

                if (goodsModel.getDetail().getStock() <= 0) return;
                long subTime = goodsModel.getDetail().getRemainSecond() - ((System.currentTimeMillis() - goodsModel.getDetail().getThisTime()) / 1000);
                if (subTime > 0) return;
                if (view.getId() == R.id.tv_batch) {
                    GoodsBatchActivity.startActivity(mContext, String.valueOf(goodsId), goodsModel.getDetail().getGoods_name(), goodsModel.getDetail().getImage());
                    return;
                }
                showSku(view.getId() == R.id.view_add_car);
            }
            break;
        }
    }


    private void showSku(boolean addCar) {
        if (goodsModel.getDetail().getStock() <= 0) {
            toast("商品已售罄");
            return;
        }
        skuView.setData(goodsModel, addCar, rlMain);
        skuView.show();
    }


    public void buy(SpecListModel specListModel, int num, boolean addCart) {
        if (addCart) {
            addCart((specListModel != null ? String.valueOf(specListModel.getGoods_spec_id()) : null), num);
        } else {
            CartListModel cartListModel = new CartListModel();
            String img = (specListModel != null ? specListModel.getForm().getSpec_image() : goodsModel.getDetail().getImage());
            cartListModel.setImages(img);
            cartListModel.setGoods_name(goodsModel.getDetail().getGoods_name());
            double price = (specListModel != null ? specListModel.getForm().getGoods_price() : goodsModel.getDetail().getGoods_price());
            double rebate_price = (specListModel != null ? specListModel.getForm().getRebate_price() : goodsModel.getDetail().getRebate_price());
            cartListModel.setRebate_price(rebate_price);
            cartListModel.setGoods_price(price);
            cartListModel.setBuy_num(num);
            cartListModel.setSpec_value(specListModel == null ? "" : specListModel.getSpec_value());
            cartListModel.setGoods_id(goodsModel.getDetail().getGoods_id());
            cartListModel.setGoods_spec_id(String.valueOf(specListModel == null ? goodsModel.getDetail().getGoods_id() : specListModel.getGoods_spec_id()));
            NewGoodsOrderActivity.startActivity(mContext, cartListModel, addressModel);
        }
    }


    private void addCart(String goods_spec_id, int num) {
        new HttpRequest<DefaultResponse>()
                .with(this).setApiCode(ApiCst.cartAdd)
                .addParam("goods_id", goodsModel.getDetail().getGoods_id())
                .addParam("token", App.getToken(mContext))
                .addParam("goods_num", num)
                .addParam("goods_spec_id", goods_spec_id)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        toast(response.message);
                        carList++;
                        tvGoodsCount.setVisibility(carList > 0 ? View.VISIBLE : View.GONE);
                        tvGoodsCount.setText(String.valueOf(carList));
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                    }
                }).start(new DefaultResponse());
    }


    private int identity;
    private int userStatus;
    private UserInfoModel userInfoModel;

    private void setAccountState() {
        if (packCommonModel == null || goodsModel == null) {
            setAccountState("加载中...", false, false);
            return;
        }

        if (userInfoModel == null) {
            if (packCommonModel.getIs_open() == 1) {
                if (packCommonModel.getPack_goods_id() == goodsId) {
                    setAccountState(null, false, false);
                } else {
                    setAccountState("购买" + packCommonModel.getPack_price() + "大礼包\n立即升级团长", true, true);
                }
            } else {
                setAccountState("成为团长后才能下单哦，立即申请", true, true);
            }
            return;
        }

        identity = userInfoModel.getIdentity();
        userStatus = userInfoModel.getStatus();
        unregisterTimer();
        if (identity == 1) {
            if (goodsModel.getDetail().getStock() > 0) {
                setAccountState(null, false, false);
                registerTimer();
            } else {
                setAccountState("商品已售罄", false, false);
            }
            return;
        }

        if (userStatus == 0) {
            setAccountState("团长入驻审核中，请耐心等待", false, true);
        } else if (userStatus == -1) {
            if (packCommonModel.getIs_open() == 1) {
                if (packCommonModel.getPack_goods_id() == goodsId) {
                    setAccountState(null, false, false);
                } else {
                    setAccountState("购买" + packCommonModel.getPack_price() + "大礼包\n立即升级团长", true, true);
                }
            } else {
                setAccountState("成为团长后才能下单哦，立即申请", true, true);
            }
        } else if (userStatus == 10) {
            setAccountState("团长入驻不通过，点击查看原因", true, false);
        } else if (userStatus == 20) {
            setAccountState("等待平台发货，升级团长", true, true);
        } else if (userStatus == 99) {
            setAccountState("账户被禁用，请重新登录", false, false);
        }


    }

    private void setAccountState(String text, boolean showImg, boolean mainColor) {
        if (text == null) {
            llAccountState.setVisibility(View.GONE);
            if (identity == 1)
                tvBatch.setVisibility(View.VISIBLE);
            if (goodsModel != null && goodsModel.getDetail() != null && goodsModel.getDetail().getIs_pack() == 1) {
                viewAddCar.setVisibility(View.GONE);
            } else {
                viewAddCar.setVisibility(View.VISIBLE);
            }

            return;
        }
        llAccountState.setVisibility(View.VISIBLE);
        llAccountState.setBackgroundColor(getResources().getColor(mainColor ? R.color.main_color : R.color.bg_E8E8E8));
        tvBatch.setVisibility(View.GONE);
        tvAccountState.setVisibility(View.VISIBLE);
        tvAccountState.setText(text);
        Drawable drawable = null;
        if (showImg) {
            drawable = getResources().getDrawable(R.drawable.img_goods_account_in);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        }
        tvAccountState.setCompoundDrawables(null, null, drawable, null);
    }

    private void getGoodsData() {
        new HttpRequest<GoodsResponse>()
                .with(this).setApiCode(ApiCst.getGoodsDetail)
                .addParam("token", App.getToken(mContext))
                .addParam("goods_id", goodsModel.getDetail().getGoods_id() == -1 ? null : goodsModel.getDetail().getGoods_id())
                //.addParam("goods_code", goodsModel.getGoods_code())
                .setListener(new HttpRequest.OnNetworkListener<GoodsResponse>() {
                    @Override
                    public void onSuccess(GoodsResponse response) {
                        goodsModel = response.getModels();
                        setGoodsView();
                        tvGoodsCount.setVisibility(carList > 0 ? View.VISIBLE : View.GONE);
                        tvGoodsCount.setText(String.valueOf(carList));
                    }

                    @Override
                    public void onFail(String message, GoodsResponse response) {
                        toast(message);
                    }
                }).start(new GoodsResponse());
    }


    private void setGoodsView() {
        if (goodsModel == null) return;

        setAccountState();

        imgView.setData(goodsModel.getDetail().getImgs_url(), goodsModel.getDetail().getMain_video(), goodsModel.getDetail().getMain_video_img());
        imgView.setOnItemPageClick(this);

        if (!TextUtils.isEmpty(goodsModel.getDetail().getDetail_video())) {
            videoViewDetail.setVisibility(View.VISIBLE);
            videoViewDetail.loadCoverImage(goodsModel.getDetail().getDetail_video_img());
            videoViewDetail.setUpLazy(goodsModel.getDetail().getDetail_video(), true, null, null, null);
        } else {
            videoViewDetail.setVisibility(View.GONE);
        }


        onPageChange(0, goodsModel.getDetail().getImgs_url() == null ? 0 : goodsModel.getDetail().getImgs_url().size());
        setText(tvPrice, String.valueOf(PriceUtils.getPriceText2(goodsModel.getDetail().getGoods_price())));


        if (goodsModel.getDetail().getRebate_price() > 0 || goodsModel.getDetail().getMin_rebate_price() > 0 || goodsModel.getDetail().getMax_rebate_price() > 0) {
            llZhuan.setVisibility(View.VISIBLE);
            tvCarRebate.setVisibility(View.VISIBLE);
            tvPayRebate.setVisibility(View.VISIBLE);
            String rabate;
            if (goodsModel.getDetail().getMin_rebate_price() > 0 || goodsModel.getDetail().getMax_rebate_price() > 0) {
                if (goodsModel.getDetail().getMax_rebate_price() == goodsModel.getDetail().getMin_rebate_price()) {
                    rabate = PriceUtils.getPriceText2(goodsModel.getDetail().getMin_rebate_price());
                } else {
                    rabate = PriceUtils.getPriceText2(goodsModel.getDetail().getMin_rebate_price()) + "-" + PriceUtils.getPriceText2(goodsModel.getDetail().getMax_rebate_price());
                }
            } else {
                rabate = PriceUtils.getPriceText2(goodsModel.getDetail().getRebate_price());
            }
            tvCarRebate.setText("(赚" + rabate + ")");
            tvPayRebate.setText("(赚" + rabate + ")");
            setText(tvZhuanPrice, rabate);
        } else {
            llZhuan.setVisibility(View.GONE);
            tvCarRebate.setVisibility(View.GONE);
            tvPayRebate.setVisibility(View.GONE);
        }

        if (identity == 1) {
            //tvPriceName.setText("进货价：");

        } else {
            //tvPriceName.setText("原价：");
            llZhuan.setVisibility(View.GONE);
        }

        if (goodsModel.getDetail().getLine_price() <= 0.0d) {
            tvOldPrice.setVisibility(View.GONE);
        } else
            setText(tvOldPrice, "¥" + PriceUtils.getPriceText2(goodsModel.getDetail().getLine_price()));


        String title = goodsModel.getDetail().getGoods_name() == null ? "" : goodsModel.getDetail().getGoods_name();
        String subtitle = goodsModel.getDetail().getSubtitle() == null ? "" : goodsModel.getDetail().getSubtitle();
        tvGoodsTitle.setText(title);
        tvGoodsSubTitle.setText(subtitle);

        if (goodsModel.getDetail().getPost_fee() > 0) {
            tvFreight.setText(PriceUtils.getPriceText2(goodsModel.getDetail().getPost_fee()) + "元");
            tvCity.setText(TextUtils.isEmpty(goodsModel.getDetail().getPost_fee_city()) ? "" : goodsModel.getDetail().getPost_fee_city());
        } else if (goodsModel.getDetail().getPost_fee() == 0) {
            tvFreight.setText("包邮");
            tvCity.setText(TextUtils.isEmpty(goodsModel.getDetail().getPost_fee_city()) ? "" : goodsModel.getDetail().getPost_fee_city());
        } else {
            refreshAddress();
        }
        llDescribe.removeAllViews();


        if (goodsModel.getParam() != null && goodsModel.getParam().size() > 0) {
            llDescribe.setVisibility(View.VISIBLE);
            rlDescribe.setVisibility(View.VISIBLE);
            viewDescribe.setVisibility(View.VISIBLE);
            for (GoodsParamModel model : goodsModel.getParam()) {
                View view = mInflater.inflate(R.layout.layout_goods_describe_item, llDescribe, false);
                llDescribe.addView(view);
                TextView tvConfigName = (TextView) view.findViewById(R.id.tv_config_name);
                TextView tvConfigContent = (TextView) view.findViewById(R.id.tv_config_content);
                setText(tvConfigName, model.getParam_key());
                setText(tvConfigContent, model.getParam_value());
            }
        } else {
            llDescribe.setVisibility(View.GONE);
            rlDescribe.setVisibility(View.GONE);
            viewDescribe.setVisibility(View.GONE);
        }

        if (goodsModel == null) return;
        if (webView == null) return;
        webView.loadDataWithBaseURL(null, HtmlFormat.getNewContent(goodsModel.getDetail().getContent()), "text/html", "utf-8", null);


    }


    private void showWhiteTitle(boolean show) {
        if (show && llTitleW.getVisibility() == View.VISIBLE) return;
        if ((!show) && llTitleT.getVisibility() == View.VISIBLE) return;
        llTitleW.setVisibility(show ? View.VISIBLE : View.GONE);
        llTitleT.setVisibility(show ? View.GONE : View.VISIBLE);
        GSYVideoManager.releaseAllVideos();
    }


    @Override
    public void onItemPage(int position) {

    }

    @Override
    public void onPageChange(int position, int allCount) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
    }


    private int scrollY = 0;

    @Override
    public void onScrollChanged(int y) {
        if (scrollY == 0)
            scrollY = CommonUtils.getScreenSize(this)[0] + CommonUtils.dip2px(mContext, 100);
        showWhiteTitle(y > scrollY);
    }

    private void getUserInfo() {
        if (!App.isLogin()) {
            tvBatch.setVisibility(View.GONE);
            llAccountState.setVisibility(View.VISIBLE);
            tvAccountState.setText("成为团长后才能下单哦，立即申请");
            return;
        }
        new HttpRequest<UserInfoResponse>()
                .with(getActivity())
                .setApiCode(ApiCst.userinfo)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<UserInfoResponse>() {

                    @Override
                    public void onSuccess(UserInfoResponse response) {
                        carList = response.cart_num;
                        tvGoodsCount.setVisibility(carList > 0 ? View.VISIBLE : View.GONE);
                        tvGoodsCount.setText(String.valueOf(carList));
                        userInfoModel = response.userInfoModel;
                        if (userInfoModel == null) return;
                        SharedPreferencesUtils.setUser(getActivity(), userInfoModel);
                        setAccountState();
                    }

                    @Override
                    public void onFail(String message, UserInfoResponse response) {

                    }
                }).start(new UserInfoResponse());
    }


    private CountDownTimer timer;

    private void registerTimer() {
        unregisterTimer();
        long subTime = goodsModel.getDetail().getRemainSecond() - ((System.currentTimeMillis() - goodsModel.getDetail().getThisTime())) / 1000;
        if (subTime <= 0) return;
        setAccountState("距团购开始99:99:99", false, true);
        timer = new CountDownTimer(subTime * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                refreshTime();
            }

            @Override
            public void onFinish() {
                refreshTime();
            }
        }.start();
    }


    private void unregisterTimer() {
        if (timer != null) timer.cancel();
        timer = null;
    }

    boolean inRefreshTime = false;

    public void refreshTime() {
        if (inRefreshTime) return;
        inRefreshTime = true;
        long subTime = goodsModel.getDetail().getRemainSecond() - ((System.currentTimeMillis() - goodsModel.getDetail().getThisTime()) / 1000);
        if (subTime > 0) {
            String[] time = DateUtils.secToTime(subTime);
            String times = time[0] + ":" + time[1] + ":" + time[2];
            tvAccountState.setText("距团购开始" + times);
            inRefreshTime = false;
        } else {
            unregisterTimer();
            setAccountState();
            inRefreshTime = false;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 221 && data != null) {
            addressModel = (AddressModel) data.getSerializableExtra("model");
            getFreight();
        }
    }

    //加载默认地址
    private void refreshAddress() {
        new HttpRequest<AddressResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .setApiCode(ApiCst.getAddressList)
                .setListener(new HttpRequest.OnNetworkListener<AddressResponse>() {
                    @Override
                    public void onSuccess(AddressResponse response) {
                        List<AddressModel> list = response.getList();
                        if (list == null || list.size() == 0) return;
                        for (AddressModel addressModel : list) {
                            if (addressModel != null && addressModel.getIsdefault() == 1) {
                                GoodsActivity.this.addressModel = addressModel;
                                getFreight();
                                return;
                            }
                        }
                    }

                    @Override
                    public void onFail(String message, AddressResponse response) {
                        getFreight();
                    }
                })
                .start(new AddressResponse());
    }

    private void getFreight() {
        if (addressModel == null) return;
        if (addressModel.getArea() == null) return;
        tvCity.setText(addressModel.getArea().getCity());
        new HttpRequest<DefaultResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .addParam("goods_id", goodsId)
                .addParam("is_cart", 2)
                .addParam("goods_num", 1)
                .addParam("address_id", addressModel.getAddress_id())
                .setApiCode(ApiCst.getPostfee)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        JSONObject object = null;
                        try {
                            object = new JSONObject(response.content);
                            freight = object.optDouble("post_fee", 0);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (freight > 0) {
                            tvFreight.setText("运费" + freight + "元");
                        } else {
                            tvFreight.setText("包邮");
                        }
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        HCUtils.loadFail(mContext, message);
                    }
                })
                .start(new DefaultResponse());
    }

    private PackCommonModel packCommonModel;

    private void getPackCommon() {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .setApiCode(ApiCst.getPackCommon)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        if (TextUtils.isEmpty(response.content)) {
                            packCommonModel = null;
                        } else {
                            packCommonModel = App.getGson().fromJson(response.content, PackCommonModel.class);
                        }
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        HCUtils.loadFail(mContext, message);
                    }
                })
                .start(new DefaultResponse());
    }


}
